package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.UploadFileUtil;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
public class VodServiceImpl implements VodService {

    private final VodConstantProperties vodConstant;
    private final VodUploadClient vodUploadClient;
    private final VodClient vodClient;

    public VodServiceImpl(VodConstantProperties vodConstant, VodUploadClient vodUploadClient, VodClient vodClient) {
        this.vodConstant = vodConstant;
        this.vodUploadClient = vodUploadClient;
        this.vodClient = vodClient;
    }

    @Override
    public Map<String, String> uploadTrack(MultipartFile file) {
        // 创建期望返回的map集合
        Map<String, String> resultMap = new HashMap<>();
        // 将上传文件保存到临时上传目录下
        String uploadTempPath = UploadFileUtil.uploadTempPath(this.vodConstant.getTempPath(), file);
        // 创建上传请求对象
        VodUploadRequest uploadRequest = new VodUploadRequest(uploadTempPath);
        // 调用客户端对象上传文件
        try {
            VodUploadResponse uploadResponse = this.vodUploadClient.upload(this.vodConstant.getRegion(), uploadRequest);
            // 解析响应结果封装返回结果
            if (uploadResponse != null) {
                resultMap.put("mediaFileId", uploadResponse.getFileId());
                resultMap.put("mediaUrl", uploadResponse.getMediaUrl());
                log.info("[专辑服务]上传音频文件到点播平台成功：文件：{}，结果：{}", file, resultMap);
            }
            // 删除临时文件
            UploadFileUtil.deleteTempFile(uploadTempPath);
        } catch (Exception e) {
            log.error("[专辑服务]上传音频文件到点播平台异常：文件：{}，错误信息：{}", file, e.getMessage(), e);
            throw new GuiguException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }

        return resultMap;
    }

    @Override
    public TrackMediaInfoVo getTrackMediaInfo(String mediaFileId) {
        // 创建期望返回的媒体信息对象
        TrackMediaInfoVo trackMediaInfoVo = new TrackMediaInfoVo();

        // 创建文件详情请求对象
        DescribeMediaInfosRequest mediaInfosRequest = new DescribeMediaInfosRequest();
        // 封装文件唯一标识
        mediaInfosRequest.setFileIds(new String[]{mediaFileId});

        // 调用文件客户端对象获取文件详情
        try {
            DescribeMediaInfosResponse mediaInfosResponse = this.vodClient.DescribeMediaInfos(mediaInfosRequest);
            // 解析响应数据封装返回结果
            if (mediaInfosResponse != null) {
                MediaInfo[] mediaInfoSet = mediaInfosResponse.getMediaInfoSet();
                if (ArrayUtil.isNotEmpty(mediaInfoSet)) {
                    MediaInfo mediaInfo = mediaInfoSet[0];
                    MediaBasicInfo basicInfo = mediaInfo.getBasicInfo();
                    trackMediaInfoVo.setType(basicInfo.getType());
                    trackMediaInfoVo.setMediaUrl(basicInfo.getMediaUrl());

                    MediaMetaData metaData = mediaInfo.getMetaData();
                    trackMediaInfoVo.setDuration(metaData.getDuration());
                    trackMediaInfoVo.setSize(metaData.getSize());
                }
            }
        } catch (TencentCloudSDKException e) {
            log.error("[专辑服务]获取点播平台文件：{}，详情异常：{}", mediaFileId, e.getMessage(), e);
            throw new GuiguException(ResultCodeEnum.TRACK_MEDIA_INFO_ERROR);
        }
        return trackMediaInfoVo;
    }

    @Override
    public void deleteTrackMedia(String mediaFileId) {
        // 创建删除文件请求对象
        DeleteMediaRequest deleteMediaRequest = new DeleteMediaRequest();
        // 封装文件唯一标识
        deleteMediaRequest.setFileId(mediaFileId);
        // 调用文件客户端对象删除文件
        try {
            this.vodClient.DeleteMedia(deleteMediaRequest);
            log.info("[专辑服务]删除点播平台文件：{}，成功", mediaFileId);
        } catch (TencentCloudSDKException e) {
            log.error("[专辑服务]删除点播平台文件：{}，失败：{}", mediaFileId, e.getMessage(), e);
        }
    }
}
